local extension = Package("heroes_com2")
extension.extensionName = "evolution"
--extension.game_modes_whitelist = {"brokenroyal_mode"}

local EV = require "packages/evolution/EV"
local U = require "packages/utility/utility"

Fk:loadTranslationTable{
    ["heroes_com2"] = "旧约角色02",
    ["com"] = "旧约",
  }

local emiya = General(extension, "com__emiya", "com", 4)

local ev__jianzhi = fk.CreateTriggerSkill{
  name = "ev__jianzhi",
  anim_type = "offensive",
  events ={fk.EventPhaseStart, fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.EventPhaseStart then
        return player.phase == Player.Start and #table.filter(player.room.discard_pile,
        function(id) return Fk:getCardById(id).sub_type == Card.SubtypeWeapon or Fk:getCardById(id).sub_type == Card.SubtypeArmor end) > 0
      else
        return data.card.type == Card.TypeEquip and player.phase ~= Player.NotActive
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local cards = table.filter(player.room.discard_pile,
      function(id) return Fk:getCardById(id).sub_type == Card.SubtypeWeapon or Fk:getCardById(id).sub_type == Card.SubtypeArmor end)
      local choice = U.askforChooseCardsAndChoice(player, cards, {"OK"}, self.name, "请选择置于牌堆顶的牌")
      room:moveCardTo(choice[1], Card.DrawPile, nil, fk.ReasonPut, self.name, nil, true)
    elseif event == fk.CardUseFinished then
      room:setPlayerMark(player, "BypassTimesLimit", 1)
      U.askForUseVirtualCard(room, player, "ev__slash", nil, self.name, nil, true, true, true)
      room:setPlayerMark(player, "BypassTimesLimit", 0)
    end
  end,
}

emiya:addSkill(ev__jianzhi)

Fk:loadTranslationTable{
  ["com__emiya"] = "英灵卫宫",
  ["designer:com__emiya"] = "zengyouyu",
  ["ev__jianzhi"] = "无限剑制",
  [":ev__jianzhi"] = "准备阶段，你可将弃牌堆里的一张武器牌或防具牌置于牌堆顶。当你于回合内使用的装备牌结算结束后，你视为使用【杀】（无距离限制）。",
}

local liangyishi = General(extension, "com__liangyishi", "com", 4, 4, General.Female)

local ev__deatheyes = fk.CreateTriggerSkill{
  name = "ev__deatheyes",
  anim_type = "offensive",
  events ={fk.EventPhaseStart, fk.TargetSpecified, fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.EventPhaseStart then
        return target == player and player.phase == Player.Start
      elseif event == fk.TargetSpecified then
        return target == player and player.phase ~= Player.NotActive and table.contains(U.getMark(player, "deatheyes_buff"), data.card:getTypeString())
        and table.contains(U.getMark(player, "deatheyes_buff"), data.to) and player:getMark("deatheyes-turn") == 1
      elseif event == fk.EnterDying then
        return data.damage and data.damage.skillName == self.name
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local tos = room:askForChoosePlayers(player, table.map(table.filter(room:getOtherPlayers(player), function(p)
        return not p:isKongcheng() end), Util.IdMapper), 1, 1, "#deatheyes-choose", self.name, true)
      if #tos > 0 then
        self.cost_data = tos[1]
        return true
      end
    elseif event == fk.TargetSpecified then
      return room:askForSkillInvoke(player, self.name, nil, "#deatheyes-damage::"..data.to)
    elseif event == fk.EnterDying then
      local cards = room:askForDiscard(player, 1, 1, true, self.name, true,  "." , "#deatheyes-throw::"..target.id)
      return #cards > 0
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local to = room:getPlayerById(self.cost_data)
      if table.find(to:getCardIds(Player.Hand), function(id) return Fk:getCardById(id):getMark("@@shown-inhand") == 0 end) then
        local id = player.room:askForCardChosen(player, to, {
          card_data = {
            {to.general, table.filter(to:getCardIds(Player.Hand), function(id) return Fk:getCardById(id):getMark("@@shown-inhand") == 0 end)},
          }
        }, self.name)
        if id >= 0 then
          to:showCards({id})
          room:setPlayerMark(player, "deatheyes_buff", {Fk:getCardById(id):getTypeString(), self.cost_data})
        end
      end
    elseif event == fk.TargetSpecified then
      room:damage({
        from = player,
        to = room:getPlayerById(data.to),
        damage = 1,
        damageType = fk.NormalDamage,
        skillName = self.name
      })
    elseif event == fk.EnterDying then
      room:killPlayer({who = target.id,})
    end
  end,

  refresh_events = fk.TargetSpecified,
  can_refresh = function(self, event, target, player, data)
    return target == player and player.phase ~= Player.NotActive and table.contains(U.getMark(player, "deatheyes_buff"), data.card:getTypeString())
    and table.contains(U.getMark(player, "deatheyes_buff"), data.to)
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:addPlayerMark(player, "deatheyes-turn")
  end,
}

liangyishi:addSkill(ev__deatheyes)

Fk:loadTranslationTable{
  ["com__liangyishi"] = "两仪式",
  ["designer:com__liangyishi"] = "zengyouyu",
  ["ev__deatheyes"] = "直死魔眼",
  [":ev__deatheyes"] = "准备阶段，你可观看一名其他角色的所有手牌并展示其中一张牌，当你于本回合内首次使用与此牌类别相同的牌指定其为目标后，你可对其造成1点伤害；当其因此伤害进入濒死状态时，你可弃置一张牌，令其死亡。",
  ["#deatheyes-choose"] = "直死之魔眼：你可展示一名其他角色的一张手牌",
  ["#deatheyes-damage"] = "你可对%dest造成1点伤害",
  ["#deatheyes-throw"] = "你可弃置一张牌，令%dest死亡",
}

local fengbujue = General(extension, "com__fengbujue", "com", 4)

local ev__zhiluan = fk.CreateActiveSkill{
  name = "ev__zhiluan",
  anim_type = "control",
  prompt = "你可获得一名其他角色的X张牌",
  target_num = 1,
  card_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and not Fk:currentRoom():getPlayerById(to_select):isNude()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.tos[1])
    local mark = player:getMark("@ev__zhiluan")
    if mark == 0 then mark = 2 end
    local n = math.min(#to:getCardIds("he"), mark)
    local cards = EV.askForCardsChosen(room, player, to, n, n, "hes", self.name)
    room:moveCardTo(cards, Player.Hand, player, fk.ReasonPrey, self.name, nil, false, player.id)
    local choice = room:askForChoice(player, {"ev__zhiluan1", "ev__zhiluan2"}, self.name)
    if choice == "ev__zhiluan1" then
      mark = mark + 1
    else
      mark = 1
    end
    room:setPlayerMark(player, "@ev__zhiluan", mark)
    local n = math.min(#player:getCardIds("he"), mark)
    local cards2 = room:askForCard(player, n, n, true, self.name, false, ".", "#ev__niliuyin::"..effect.tos[1]..":"..n)
    room:moveCardTo(cards2, Player.Hand, to, fk.ReasonGive, self.name, nil, false, player.id)
  end,
}

fengbujue:addSkill(ev__zhiluan)

Fk:loadTranslationTable{
  ["com__fengbujue"] = "封不觉",
  ["designer:com__fengbujue"] = "zengyouyu",
  ["ev__zhiluan"] = "智乱",
  ["@ev__zhiluan"] = "智乱",
  [":ev__zhiluan"] = "阶段技（1），你可获得一名其他角色的X张牌并选择一项：1.令X+1；2.重置X为1。选择完毕后，你将X张牌交给其（X初始为2）。",
  ["ev__zhiluan1"] = "X+1",
  ["ev__zhiluan2"] = "重置X为1",
}

local sakura = General(extension, "com__sakura", "com", 3, 3, General.Female)
local lingbian_put = fk.CreateTriggerSkill{
  name = "#ev__lingbian_put",
  anim_type = "special",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and U.hasFullRealCard(player.room, data.card) and not data.card:isVirtual()
    and data.card.type == Card.TypeTrick and data.card.sub_type ~= Card.SubtypeDelayedTrick
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:addToPile("spirit", data.card, true, self.name)
    if #player:getPile("spirit") > player.maxHp then
      local n = #player:getPile("spirit") - player.maxHp
      local card = room:askForCard(player, n, n, false, self.name, true, ".|.|.|spirit|.|.", "#ev__lingbian-throw", "spirit")
      if #card > 0 then
        room:moveCardTo(card, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, "", "", true)
      end
    end
  end,
}

local function removeDuplicates(t)
  local seen = {}
  local result = {}
  for _, v in ipairs(t) do
      if not seen[v] then
          seen[v] = true
          table.insert(result, v)
      end
  end
  return result
end

local ev__lingbian = fk.CreateViewAsSkill{
  name = "ev__lingbian",
  prompt = "你可将一张牌当一张“灵”使用",
  interaction = function()
    local names = table.map(Self:getPile("spirit"), function(id) return Fk:getCardById(id).name end)
    return U.CardNameBox {choices = removeDuplicates(names)}
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcard(cards[1])
    card.skillName = self.name
    return card
  end,

  after_use = function(self, player, use)
    local room = player.room
    local cards = room:askForCard(player, 2, 2, false, self.name, true, ".|.|.|spirit|.|.", "#ev__lingbian-reset", "spirit")
    if #cards > 0 then
      room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, "", "", true) 
      player:addSkillUseHistory(self.name, -1, Player.HistoryPhase)
    end
  end,
}

ev__lingbian:addRelatedSkill(lingbian_put)
sakura:addSkill(ev__lingbian)

local ev__xingyou = fk.CreateTriggerSkill{
  name = "ev__xingyou",
  anim_type = "defensive",
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self.name) and player:isKongcheng() then
      return #player.room.logic:getEventsOfScope(GameEvent.Damage, 999, function (e)
        local damage = e.data[1]
        if damage and player == damage.to then
          return true
        end
      end, Player.HistoryTurn) == 1
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
    return true
  end,
}

sakura:addSkill(ev__xingyou)

Fk:loadTranslationTable{
  ["com__sakura"] = "木之本樱",
  ["designer:com__sakura"] = "zengyouyu&KINGDOM43",
  ["ev__lingbian"] = "灵变",
  ["#ev__lingbian_put"] = "灵变",
  ["spirit"] = "灵",
  [":ev__lingbian"] = "当其他角色使用非转化的即时魔法牌因结算完毕而置入弃牌堆后，你可将之置于角色牌上，称为“灵”并将“灵”弃至体力上限。"..
  "<br />阶段技（1），你可将一张牌当一张“灵”使用，然后你可弃两张“灵”，重置此技能。",
  ["#ev__lingbian-throw"] = "请将“灵”弃至体力上限",
  ["#ev__lingbian-reset"] = "你可弃两张“灵”，重置“灵变”",

  ["ev__xingyou"] = "星佑",
  [":ev__xingyou"] = "当你于当前回合内首次受到伤害时，若你没有手牌，则你可防止此伤害，摸一张牌。",
}

local suona = General(extension, "com__suona", "com", 3, 3, General.Female)

local ev__hexian = fk.CreateViewAsSkill{
  name = "ev__hexian&",
  pattern = "^nullification",
  interaction = function()
    local all_names = U.getAllCardNames("b")
    table.removeOne(all_names, "ev__poison")
    local invoke_names = {}
    local mark = U.getMark(Self, "hexian_card")
    for _, id in ipairs(mark) do
      table.insertIfNeed(invoke_names, Fk:getCardById(id).name)
    end
    if #invoke_names > 0 then
      return U.CardNameBox { choices = invoke_names, all_choices = all_names }
    end
  end,
  expand_pile = function()--耦
    if Self:getMark("caikuang-turn") == 0 and Self:getMark("ev__caikuang") ~= 0 then
      return {Self:getMark("ev__caikuang")}
    end
  end,
  card_filter = function(self, to_select, selected)
    if not self.interaction.data or #selected > 0 then return false end
    local cards = table.filter(U.getMark(Self, "hexian_card"), function (id) return Fk:getCardById(id).name == self.interaction.data end)
    if #cards > 0 then
      return table.find(cards, function(id) return Fk:getCardById(id).color == Fk:getCardById(to_select).color end)
    end
  end,
  view_as = function(self, cards)
    if not self.interaction.data or #cards ~= 1 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcard(cards[1])
    card.skillName = self.name
    return card
  end,
}

Fk:addSkill(ev__hexian)

local nenglianghexian = fk.CreateActiveSkill{
  name = "nenglianghexian",
  anim_type = "support",
  card_num = 1,
  min_target_num = 1,
  prompt = "你可选择一张基础牌和距离1以内的任意名角色",
  can_use = function(self, player)
    return not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName ~= "poison" and Fk:getCardById(to_select).type == Card.TypeBasic
    and Fk:getCardById(to_select):getMark("@@shown-inhand") == 0
  end,
  target_filter = function(self, to_select, selected)
    return Self:distanceTo(Fk:currentRoom():getPlayerById(to_select)) <= 1
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    EV.OpenCards(room, player, effect.cards, self.name)
    local names = U.getMark(player, "hexian_name")
    table.insertIfNeed(names, Fk:getCardById(effect.cards[1]).trueName)
    room:setPlayerMark(player, "hexian_name", names)
    for _, p in ipairs(effect.tos) do
      local to = room:getPlayerById(p)
      if not to:hasSkill("ev__hexian&") then
        room:handleAddLoseSkills(to, "ev__hexian&")
      end
      local mark = U.getMark(to, "hexian_card")
      table.insertIfNeed(mark, effect.cards[1])
      room:setPlayerMark(to, "hexian_card", mark)
    end
  end,
}

local nenglianghexian_trigger = fk.CreateTriggerSkill{
  name = "#nenglianghexian-trigger",
  --mute = true,
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and data.card.type == Card.TypeBasic and #U.getMark(player, "hexian_name") > 0 then
      return table.contains(U.getMark(player, "hexian_name"), data.card.trueName) and player:distanceTo(target) <= 1
    end
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#nenglianghexian-invoke::"..target.id)
  end,
  on_use = function(self, event, target, player, data)
    player.room:askForDiscard(target, 1, 1, true, self.name, false)
  end,

  refresh_events = {fk.TurnStart, fk.Deathed},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self, true, true) and target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "hexian_name", 0)
    for _, p in ipairs(room:getAlivePlayers()) do
      room:setPlayerMark(p, "hexian_card", 0)
    end
  end,
}

local kuangwuzhongyue = fk.CreateActiveSkill{
  name = "kuangwuzhongyue",
  anim_type = "control",
  frequency = Skill.Limited,
  prompt = "你可弃置至少一张明置手牌",
  min_card_num = 1,
  target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_filter = function(self, to_select, selected)
    return Fk:currentRoom():getCardArea(to_select) == Card.PlayerHand and Fk:getCardById(to_select):getMark("@@shown-inhand") ~= 0
  end,
  target_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:moveCardTo(effect.cards, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, "", true, player.id)
    local targets = table.filter(room.alive_players, function (p)
      return player:inMyAttackRange(p) and player:getHandcardNum() == p:getHandcardNum()
    end)
    local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 99, "#kuangwuzhongyue-choose", self.name, true)
    if #tos > 0 then
      for _, p in ipairs(tos) do
        room:getPlayerById(p):turnOver()
      end
    end
  end,
}

nenglianghexian:addRelatedSkill(nenglianghexian_trigger)
suona:addSkill(nenglianghexian)
suona:addSkill(kuangwuzhongyue)

Fk:loadTranslationTable{
  ["com__suona"] = "娑娜",
  ["designer:com__suona"] = "zengyouyu",
  ["nenglianghexian"] = "能量和弦",
  [":nenglianghexian"] = "出牌阶段，你可明置一张除【毒】外的基础牌并选择距离1以内的任意名角色，直至你的下回合开始：其可将与此牌颜色相同的牌当此牌使用；当距离1以内的角色使用与此牌牌名相同的牌时，你可令其弃置一张牌。",
  ["ev__hexian&"] = "和弦",
  [":ev__hexian&"] = "你可将一张牌当娑娜指定的基础牌使用。",
  ["#nenglianghexian-trigger"] = "能量和弦",
  ["#nenglianghexian-invoke"] = "你可令%dest弃置一张牌",
  ["kuangwuzhongyue"] = "狂舞终乐",
  [":kuangwuzhongyue"] = "限定技，出牌阶段，你可弃置至少一张明置手牌，然后你令你攻击范围内的手牌数与你相同的任意名角色翻面。",
  ["#kuangwuzhongyue-choose"] = "请选择你攻击范围内手牌数与你相同的任意名角色翻面",
}

local Yozora = General(extension, "com__yozora", "com", 3, 3, General.Female)

local ev__dushe = fk.CreateTriggerSkill{
  name = "ev__dushe",
  --mute = true,
  events = {fk.CardUsing, fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self.name) and data.card and data.card.type ~= Card.TypeEquip and data.card.sub_type ~= Card.SubtypeDelayedTrick then
      if event == fk.CardUsing then
        return player.phase ~= Player.NotActive and target ~= player
      else
        return target == player
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    --local pattern = ".|.|.|.|.|"..data.card:getTypeString()
    local pattern = string.sub(data.card:getTypeString(), 1, 1)
    if pattern == "t" then pattern = "td" end
    local all_names = U.getAllCardNames(pattern, true)
    table.removeOne(all_names, data.card.trueName)
    pattern = table.concat(all_names, ",")
    local cards = player.room:askForDiscard(player, 1, 1, true, self.name, true, pattern, "#ev__dushe-cancel:::"..data.card:toLogString())
    if #cards > 0 then
      self.cost_data = cards
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, {target.id})
    if event == fk.CardUsing then
      data.tos = {}
    else
      --table.insertIfNeed(data.nullifiedTargets, player.id)
      EV.nullifiedCard(data, data.card, player)
    end
  end,
}

Yozora:addSkill(ev__dushe)

local ev__kuangpian = fk.CreateActiveSkill{
  name = "ev__kuangpian",
  anim_type = "offensive",
  prompt = "#ev__kuangpian",
  target_num = 1,
  card_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and not target:isKongcheng() and Self.id ~= to_select
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local id = EV.askForCardChosen(room, player, target, "hs", self.name)
    local unshown = table.filter(player:getCardIds(Player.Hand), function(id) return Fk:getCardById(id):getMark("@@shown-inhand") == 0 end)
    if #unshown > 0 then
      player:showCards(unshown)
      target:showCards({id})
      if player:isKongcheng() then
        room:moveCardTo(id, Player.Hand, player, fk.ReasonPrey, self.name, nil, false, player.id)
      elseif table.every(unshown, function(cd) return Fk:getCardById(cd).trueName ~= Fk:getCardById(id).trueName end) then
        room:moveCardTo(id, Player.Hand, player, fk.ReasonPrey, self.name, nil, false, player.id)
      end
    end
  end,
}
Yozora:addSkill(ev__kuangpian)
Fk:loadTranslationTable{
  ["com__yozora"] = "三日月夜空",
  ["designer:com__yozora"] = "zengyouyu",
  ["ev__dushe"] = "毒舌",
  [":ev__dushe"] = "当一名角色/其他角色使用基础牌或即时魔法牌指定目标后，若你是此牌的目标角色/当前回合角色，你可弃置一张与此牌类别相同且牌名不同的牌，令此牌对你无效/取消所有目标。",
  ["#ev__dushe-cancel"] = "你可以弃置一张与%arg类别相同且牌名不同的牌令之无效",
  ["ev__kuangpian"] = "诳骗",
  [":ev__kuangpian"] = "阶段技（1），你可展示所有手牌和一名其他角色的一张手牌；若其展示的此牌与你展示的所有牌的牌名均不同，你获得此牌。",
  ["#ev__kuangpian"] = "你可展示所有手牌和一名其他角色的一张手牌",
}

local Hitagi = General(extension, "com__hitagi", "com", 3, 3, General.Female)

local ev__wuzhong = fk.CreateTriggerSkill{
  name = "ev__wuzhong",
  --anim_type = "masochism",
  mute = true,
  events = {fk.Damaged, fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if event == fk.Damaged then
      return target == player and player:hasSkill(self) and data.card and player.room:getCardArea(data.card) == Card.Processing
    else
      return player:usedSkillTimes(self.name, Player.HistoryTurn) > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.Damaged then
      return player.room:askForSkillInvoke(player, self.name)
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.Damaged then
      local room = player.room
      local toPut = data.card:isVirtual() and data.card.subcards or { data.card.id }
      local choice = room:askForChoice(player, {"top", "bottom"}, self.name)
      if #toPut > 1 then
        if choice == "top" then
          toPut = room:askForGuanxing(player, toPut, { #toPut, #toPut }, { 0, 0 }, self.name, true).top
        else
          toPut = room:askForGuanxing(player, toPut, { 0, 0 }, { #toPut, #toPut }, self.name, true).bottom
        end
        toPut = table.reverse(toPut)
      end
      player.room:notifySkillInvoked(player, self.name, "masochism")
      if choice == "top" then
        room:moveCardTo(toPut, Card.DrawPile, nil, fk.ReasonPut, self.name, nil, true)
      else
        room:moveCards({
          ids = toPut,
          --from = Card.Processing,
          toArea = Card.DrawPile,
          moveReason = fk.ReasonPut,
          skillName = self.name,
          drawPilePosition = -1,
        })
      end
    else
      local num = 1
      local events = player.room.logic:getEventsOfScope(GameEvent.ChangeHp, 999, function (e)
        local damage = e.data[5]
        if damage and player == damage.to then
          num = num + damage.damage
        end
      end, Player.HistoryTurn)
      player.room:notifySkillInvoked(player, self.name, "drawcard")
      player:drawCards(num, self.name)
    end
  end,
}

local ev__juqi = fk.CreateViewAsSkill{
  name = "ev__juqi",
  pattern = "slash,jink",
  prompt = function ()
    return "#ev__juqi-card"
  end,
  interaction = function()
    local names = {}
    for _, name in ipairs({"slash","jink"}) do
      local card = Fk:cloneCard(name)
      if (Fk.currentResponsePattern == nil and Self:canUse(card)) or
        (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card)) then
        table.insertIfNeed(names, "ev__"..card.name)
      end
    end
    if #names == 0 then return end
    return UI.ComboBox {choices = names}
  end,
  card_filter = function (self, to_select, selected)
    local card = Fk:getCardById(to_select)
    return #selected == 0 and card.type == Card.TypeEquip
  end,
  before_use = function (self, player, use)
    local room = player.room
    local put = use.card:getMark(self.name)
    if put ~= 0 and table.contains(player:getCardIds("he"), put) then
      local choices = {"ev__juqi1"}
      if room:getCardArea(put) == Card.PlayerHand and not table.contains(U.getMark(player, "@$shown"), put) then
        table.insertIfNeed(choices, "ev__juqi2")
      end
      local choice = room:askForChoice(player, choices, self.name)
      if choice == "ev__juqi2" then
        EV.OpenCards(room, player, put, self.name)
      else
        room:moveCardTo(put, Card.DiscardPile, nil, fk.ReasonDisCard, "", "", true)
      end
    end
    room:setCardMark(use.card, self.name, 0)
  end,
  view_as = function(self, cards)
    if not self.interaction.data or #cards ~= 1 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:setMark(self.name, cards[1])
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return not player:isNude()
  end,
  enabled_at_response = function(self, player, response)
    return not player:isNude()
  end,
}

local ev__juqi_maxcards = fk.CreateMaxCardsSkill{
  name = "#ev__juqi_maxcards",
  exclude_from = function(self, player, card)
    return player:hasSkill(self) and card.type == Card.TypeEquip
  end,
}

Hitagi:addSkill(ev__wuzhong)
ev__juqi:addRelatedSkill(ev__juqi_maxcards)
Hitagi:addSkill(ev__juqi)

Fk:loadTranslationTable{
  ["com__hitagi"] = "战场原黑仪",
  ["designer:com__hitagi"] = "南家二傻不姓南+陆丿伯言",
  ["ev__wuzhong"] = "无重",
  [":ev__wuzhong"] = "当你受到牌造成的伤害后，你可将此牌置于牌堆顶或牌堆底；若如此做，当前回合结束时，你摸X张牌（X为你于当前回合内受到过的伤害数+1）。",
  ["ev__juqi"] = "具器",
  ["#ev__juqi_maxcards"] = "具器",
  [":ev__juqi"] = "你的装备牌不计入手牌上限。当你需要使用或打出【杀】/【闪】时，你可明置或弃置一张装备牌，视为使用或打出【杀】/【闪】。",
  ["#ev__juqi-card"] = "具器：你可明置或弃置一张装备牌，视为使用或打出【杀】/【闪】",
  ["ev__juqi1"] = "弃置",
  ["ev__juqi2"] = "明置",
}


local Origami = General(extension, "com__origami", "com", 4, 4, General.Female)

local juemietianshi = fk.CreateViewAsSkill{
  name = "juemietianshi",
  pattern = "^nullification",
  interaction = function()
    local all_names = U.getAllCardNames("bt")
    local invoke_names = {"ev__jink"}
    for _, name in ipairs(all_names) do
      if Fk:cloneCard(name).is_damage_card then
        table.insertIfNeed(invoke_names, name)
      end
    end
    local names = U.getViewAsCardNames(Self, "juemietianshi", invoke_names, nil, U.getMark(Self, "juemietianshi-turn"))
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = invoke_names }
    end
  end,
  card_filter = Util.TrueFunc,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    local n = Fk:translate(card.trueName, "zh_CN"):len()
    n = math.min(n, 3)
    if #cards ~= n then return end
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    local mark = U.getMark(player, "juemietianshi-turn")
    table.insert(mark, use.card.trueName)
    player.room:setPlayerMark(player, "juemietianshi-turn", mark)
  end,
  enabled_at_response = function(self, player, response)
    return not response
  end,
}

local juemietianshi_trigger = fk.CreateTriggerSkill{
  name = "#juemietianshi_trigger",
  mute = true,
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and data.card.type == Card.TypeBasic
    and data.card.skillName == "juemietianshi" and player:getMark("juemietianshi-round") == 0
  end,
  on_cost = Util.TrueFunc,
  on_trigger = function(self, event, target, player, data)
    player.room:addPlayerMark(player, "juemietianshi-round")
    if U.hasFullRealCard(player.room, data.card) then
      player.room:obtainCard(player.id, data.card, true, fk.ReasonJustMove)
    end
  end,
}

juemietianshi:addRelatedSkill(juemietianshi_trigger)
Origami:addSkill(juemietianshi)

Fk:loadTranslationTable{
  ["com__origami"] = "鸢一折纸",
  ["designer:com__origami"] = "陆丿伯言",
  ["juemietianshi"] = "绝灭天使",
  ["#juemietianshi_trigger"] = "绝灭天使",
  [":juemietianshi"] = "每回合每个牌名限一次，你可将X张牌当可造成伤害的牌或【闪】使用；当你于本轮内首次以此法使用基础牌时，你获得此牌对应的实体牌（X为转化结果的牌名字数与3中的最小值）。",
}

local Kyouko = General(extension, "com__kyouko", "com", 4, 4, General.Female)

local ev__qiangwei = fk.CreateViewAsSkill{
  name = "ev__qiangwei",
  anim_type = "offensive",
  pattern = "slash,jink,thorn_circle",
  prompt = "#ev__qiangwei",
  interaction = function()
    local names = {}
    local pattern = {"thorn_circle"}
    if Self.phase == Player.NotActive then
      table.insertIfNeed(pattern, "ev__jink")
    end
    if Self.phase ~= Player.NotActive then
      table.insertIfNeed(pattern, "ev__slash")
    end
    for _, name in ipairs(pattern) do
      local card = Fk:cloneCard(name)
      if (Fk.currentResponsePattern == nil and Self:canUse(card)) or
        (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card)) then
        table.insertIfNeed(names, card.name)
      end
    end
    return UI.ComboBox {choices = names}
  end,
  card_filter = function(self, to_select, selected)
    if self.interaction.data == "thorn_circle" then
      return #selected == 0 and ((Fk:getCardById(to_select).suit == Card.Diamond or Fk:getCardById(to_select).trueName == "slash")
      and Fk:currentRoom():getCardArea(to_select) ~= Player.Equip)
    else
      return false
    end
  end,
  view_as = function(self, cards)
    if #cards > 1 or not self.interaction.data then return end
    if #cards == 0 and self.interaction.data == "thorn_circle" then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    if #cards == 1 then
      card:addSubcard(cards[1])
    end
    return card
  end,

  enabled_at_response = function(self, player, response)
    if not response then
      for _, p in ipairs(Fk:currentRoom().alive_players) do
        if p.phase ~= Player.NotActive and not p.chained then
          return false
        end
      end
      return true
    end
  end,
}

local qiangwei_trigger = fk.CreateTriggerSkill{
  name = "#qiangwei_trigger",
  refresh_events = {fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.skillName == "ev__qiangwei" and
     (data.card.trueName == "slash" or data.card.trueName == "jink")
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if data.card.trueName == "slash" then
      for _, id in ipairs(TargetGroup:getRealTargets(data.tos)) do
        local p = room:getPlayerById(id)
        if p.chained then
          p:setChainState(false)
        end
      end
    elseif data.card.trueName == "jink" then
      if player.room.current and player.room.current.chained then
        player.room.current:setChainState(false)
      end
    end
  end,
}

local qiangwei_prohibit = fk.CreateProhibitSkill{
  name = "#ev__qiangwei_prohibit",
  is_prohibited = function(self, from, to, card)
    return card.skillName == "ev__qiangwei" and card.trueName == "slash" and from:hasSkill(self) and not to.chained
  end,
}

ev__qiangwei:addRelatedSkill(qiangwei_trigger)
ev__qiangwei:addRelatedSkill(qiangwei_prohibit)
Kyouko:addSkill(ev__qiangwei)

local ev__hunhuo = fk.CreateTriggerSkill{
  name = "ev__hunhuo",
  anim_type = "offensive",
  frequency = Skill.Limited,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and player.phase == Player.Finish
    and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p) return not p.chained end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, 2, "#ev__hunhuo-choose", self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(self.cost_data) do
      room:getPlayerById(p):setChainState(true)
    end
    if player.hp > 1 then
      room:loseHp(player, player.hp - 1)
    end
    local n = 1
    if #table.filter(room.alive_players, function(p) return p.chained end) == 2 and room:askForSkillInvoke(player, self.name, data, "#jingzuihunhuo") then
      n = 2
    end
    room:damage({
      from = player,
      to = player,
      damage = n,
      damageType = fk.FireDamage,
      skillName = self.name,
    })
  end,
}

Kyouko:addSkill(ev__hunhuo)

Fk:loadTranslationTable{
  ["com__kyouko"] = "佐仓杏子",
  ["designer:com__kyouko"] = "陆丿伯言&zengyouyu",
  ["ev__qiangwei"] = "蔷薇教义",
  ["#ev__qiangwei_prohibit"] = "蔷薇教义",
  [":ev__qiangwei"] = "你可将一张【杀】或方块手牌当【荆棘之环】使用。当你于回合内/外需要使用【杀】/【闪】时，若一名角色/当前回合角色已横置，你可视为对其使用【杀】/使用【闪】，然后令其重置。",
  ["#ev__qiangwei"] = "你可将一张【杀】或方块手牌当【荆棘之环】使用，或不选择牌视为使用【杀】/【闪】",
  ["ev__hunhuo"] = "净罪魂火",
  [":ev__hunhuo"] = "限定技，结束阶段，你可令至多两名角色横置，然后你失去体力至1点并对自己造成1点火焰伤害；若已横置的角色仅有两名，你可改为造成2点火焰伤害。",
  ["#ev__hunhuo-choose"] = "你可令至多两名角色横置，然后你失去体力至1点并对自己造成1点火焰伤害",
  ["#jingzuihunhuo"] = "净罪魂火：你可改为造成2点火焰伤害",
}

local banben = General(extension, "com__banben", "com", 4)
local ev__wance = fk.CreateTriggerSkill{
  name = "ev__wance",
  anim_type = "special",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and not player:isKongcheng() then
      local room = player.room
      local ids = {}
      local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
      local end_id = turn_event.id
      U.getEventsByRule(room, GameEvent.MoveCards, 999, function (e)
        for _, move in ipairs(e.data) do
          if move.from and move.from == player.id and
          (move.moveReason == fk.ReasonUse or move.moveReason == fk.ReasonResonpse or move.moveReason == fk.ReasonDiscard) then
            for _, info in ipairs(move.moveInfo) do
              table.insertIfNeed(ids, info.cardId)
            end
          end
        end
        return false
      end, end_id)
      local cards = table.simpleClone(ids)
      for _, id in ipairs(cards) do
        if room:getCardArea(id) ~= Card.DiscardPile then
          table.removeOne(ids, id)
        end
      end
      if #ids > 0 then
        self.cost_data = ids
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local hands = player:getCardIds(Player.hand)
    local cards = self.cost_data
    local cids = U.askForExchange(player, self.name, player.general, cards, hands, "#wance-exchange", 1, true)
    if #cids > 0 then
      hands = table.filter(cids, function (id)
        return table.contains(player:getCardIds(Player.hand), id)
      end)
      cards = table.filter(cids, function (id)
        return not table.contains(player:getCardIds(Player.hand), id)
      end)
      local card1 = Fk:getCardById(hands[1])
      local card2 = Fk:getCardById(cards[1])
      U.swapCardsWithPile(player, hands, cards, self.name, "discardPile", true, player.id)
      if card1.trueName == card2.trueName or card1.number == card2.number then
        player:drawCards(1, self.name)
      end
    end
  end,
}

ev__wance:addRelatedSkill(EV.center_area)
banben:addSkill(ev__wance)

Fk:loadTranslationTable{
  ["com__banben"] = "坂本",
  ["designer:com__banben"] = "南家二傻不姓南&zengyouyu",
  ["ev__wance"] = "完策",
  [":ev__wance"] = "回合技（终），你可用一张手牌替换弃牌堆里你于此回合内因使用、打出或弃置而失去过的一张牌；若这两张牌的牌名或点数相同，你摸一张牌。",
  ["#wance-exchange"] = "完策：请选择一张手牌和替换的牌",
}

local huiliyi = General(extension, "com__huiliyi", "com", 3, 3, General.Female)

local ev__yinglian = fk.CreateTriggerSkill{
  name = "ev__yinglian",
  frequency = Skill.Compulsory,
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target ~= player and player:hasSkill(self) and data.card.trueName == "peach" and data.to == player.id
  end,
  on_use = function(self, event, target, player, data)
    target:drawCards(2, self.name)
  end,

  refresh_events = {fk.EventAcquireSkill, fk.EventLoseSkill, fk.BuryVictim},
  can_refresh = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill or event == fk.EventLoseSkill then
      return data == self
    elseif event == fk.BuryVictim then
      return player:hasSkill(self, true, true)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if table.every(room.alive_players, function(p) return not p:hasSkill(self, true) or p == player end) then
      if player:hasSkill("ev__yinglian&", true, true) then
        room:handleAddLoseSkills(player, "-ev__yinglian&", nil, false, true)
      end
    else
      if not player:hasSkill("ev__yinglian&", true, true) then
        room:handleAddLoseSkills(player, "ev__yinglian&", nil, false, true)
      end
    end
  end,
}

local yinglian_active = fk.CreateActiveSkill{
  name = "ev__yinglian&",
  anim_type = "support",
  card_num = 1,
  target_num = 1,
  prompt = "#ev__yinglian",
  can_use = function(self, player)
    return table.find(Fk:currentRoom().alive_players, function(p) return p ~= player and p:hasSkill(ev__yinglian, true) end)
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == "peach"
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and Fk:currentRoom():getPlayerById(to_select):hasSkill(ev__yinglian)
    and Fk:currentRoom():getPlayerById(to_select):isWounded()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local card = Fk:getCardById(effect.cards[1])
    if not player:isProhibited(target, card) then
      room:useCard({
        card = card,
        from = player.id,
        tos = {{target.id}},
        skillName = self.name,
      })
    end 
  end,
}

local ev__shenpan = fk.CreateTriggerSkill{
  name = "ev__shenpan",
  anim_type = "offensive",
  events = {fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash" and #U.getUseExtraTargets(player.room, data, true) > 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(U.getUseExtraTargets(room, data, true), function(id)
      return room:getPlayerById(id).hp <= player.hp
    end)
    local tos = room:askForChoosePlayers(player, targets, 1, 99, "#ev__shenpan-choose", self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    table.insert(data.tos, self.cost_data)
    player.room:sendLog{
      type = "#AddTargetsBySkill",
      from = player.id,
      to = self.cost_data,
      arg = self.name,
      arg2 = data.card:toLogString()
    }
  end,
}

local ev__hunzang = fk.CreateActiveSkill{
  name = "ev__hunzang",
  anim_type = "offensive",
  prompt = "#ev__hunzang",
  target_num = 0,
  card_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    for _, p in ipairs(room:getOtherPlayers(player, true)) do
      if p.hp == 1 then
        --local use = room:askForUseCard(p, "basic", ".|.|.|.|.|basic", "#ev__hunzang-use::"..player.id, true,
        --{must_targets = {player.id}, bypass_distances = true, bypass_times = true})
        local all_names = U.getAllCardNames("b", true)
        table.removeOne(all_names, "jink")
        if not player:isWounded() then
          table.removeOne(all_names, "peach")
        end
        local use = room:askForCard(p, 1, 1, true, self.name, true, table.concat(all_names, ",") , "#ev__hunzang-use::"..player.id)
        if #use > 0 then
          --room:useCard(use)
          room:useCard({
            card = Fk:getCardById(use[1]),
            from = p.id,
            tos = {{effect.from}} ,
            skillName = self.name,
            extraUse = true,
          })
        else
          room:killPlayer({who = p.id,})
        end
      end
    end
  end,
}

Fk:addSkill(yinglian_active)
huiliyi:addSkill(ev__yinglian)
huiliyi:addSkill(ev__shenpan)
huiliyi:addSkill(ev__hunzang)

Fk:loadTranslationTable{
  ["com__huiliyi"] = "上杉绘梨衣",
  ["designer:com__huiliyi"] = "zengyouyu",
  --["illustrator:com__huiliyi"] = "TAYA",
  ["ev__yinglian"] = "樱恋",
  [":ev__yinglian"] = "锁定技，若你已受伤，其他角色于其出牌阶段能对你使用【茶】。其他角色使用【茶】指定你为目标后，你令其摸两张牌。",
  ["ev__yinglian&"] = "樱恋",
  ["#ev__yinglian"] = "你可以对上杉绘梨衣使用【茶】",
  [":ev__yinglian&"] = "你可以对上杉绘梨衣使用【茶】。",
  ["ev__shenpan"] = "审判",
  [":ev__shenpan"] = "你使用的【杀】可额外选择体力值不大于你的任意名角色为目标（无距离限制）。",
  ["#ev__shenpan-choose"] = "审判：你可额外选择体力值不大于你的任意名角色",
  ["ev__hunzang"] = "魂葬",
  [":ev__hunzang"] = "限定技，出牌阶段，你可令所有体力值为1的其他角色各选择一项：1.其对你使用一张基础牌；2.其死亡。",
  ["#ev__hunzang"] = "你可令所有体力值为1的其他角色对你使用一张基础牌，否则其死亡",
  ["#ev__hunzang-use"] = "请对%dest使用一张基础牌，否则你死亡！",
}

local lilibai = General(extension, "com__lilibai", "com", 3, 3, General.Female)

local ev__chunyu = fk.CreateTriggerSkill{
  name = "ev__chunyu",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and (player.phase == Player.Start or player.phase == Player.Finish)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(player, {"ev__chunyu1","ev__chunyu2", "cancel"}, self.name)
    if choice == "ev__chunyu1" then
      local hands = table.filter(room.alive_players, function (p)
        return table.every(room:getOtherPlayers(p), function (sp) return sp:getHandcardNum() >= p:getHandcardNum() end)
        or table.every(room:getOtherPlayers(p), function (sp) return sp:getHandcardNum() <= p:getHandcardNum() end)
      end)
      for _, p in ipairs(hands) do
        if player:isAlive() and p:isAlive() and not p:isNude() then
          local id = EV.askForCardChosen(room, player, p, "hes", self.name)
          if id > 0 then
            room:moveCardTo(id, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, "", true, player.id)
          end
        end
      end
      local hps = table.filter(room.alive_players, function (p)
        return table.every(room:getOtherPlayers(p), function (sp) return sp.hp >= p.hp end)
        or table.every(room:getOtherPlayers(p), function (sp) return sp.hp <= p.hp end)
      end)
      for _, p in ipairs(hps) do
        p:drawCards(1, self.name)
      end
    elseif choice == "ev__chunyu2" then
      local hps = table.filter(room.alive_players, function (p)
        return table.every(room:getOtherPlayers(p), function (sp) return sp.hp >= p.hp end)
        or table.every(room:getOtherPlayers(p), function (sp) return sp.hp <= p.hp end)
      end)
      for _, p in ipairs(hps) do
        if player:isAlive() and p:isAlive() and not p:isNude() then
          local id = EV.askForCardChosen(room, player, p, "hes", self.name)
          if id > 0 then
            room:moveCardTo(id, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, "", true, player.id)
          end
        end
      end
      local hands = table.filter(room.alive_players, function (p)
        return table.every(room:getOtherPlayers(p), function (sp) return sp:getHandcardNum() >= p:getHandcardNum() end)
        or table.every(room:getOtherPlayers(p), function (sp) return sp:getHandcardNum() <= p:getHandcardNum() end)
      end)
      for _, p in ipairs(hands) do
        p:drawCards(1, self.name)
      end
    end
  end,

  refresh_events = {fk.EventPhaseStart},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and (player.phase == Player.Start or player.phase == Player.Finish)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local hands = table.filter(room.alive_players, function (p)
      return table.every(room:getOtherPlayers(p), function (sp) return sp:getHandcardNum() >= p:getHandcardNum() end)
      or table.every(room:getOtherPlayers(p), function (sp) return sp:getHandcardNum() <= p:getHandcardNum() end)
    end)
    local hps = table.filter(room.alive_players, function (p)
      return table.every(room:getOtherPlayers(p), function (sp) return sp.hp >= p.hp end)
      or table.every(room:getOtherPlayers(p), function (sp) return sp.hp <= p.hp end)
    end)
    table.forEach(hands, function (p) return room:addPlayerMark(p, "@@chunyu_hand-phase") end)
    table.forEach(hps, function (p) return room:addPlayerMark(p, "@@chunyu_hp-phase") end)
  end,
}

lilibai:addSkill(ev__chunyu)

Fk:loadTranslationTable{
  ["com__lilibai"] = "莉莉白",
  ["designer:com__lilibai"] = "啊啊啊啊山世",
  ["ev__chunyu"] = "春语",
  [":ev__chunyu"] = "准备阶段或结束阶段，你可选择一项，弃置满足此项的角色各一张牌，然后令满足另一项的角色各摸一张牌：1.手牌数最大或最小；2.体力值最大或最小。",
  ["ev__chunyu1"] = "手牌数最大或最小",
  ["ev__chunyu2"] = "体力值最大或最小",
  ["@@chunyu_hand-phase"] = "<font color=\"#7DF9FF\">手牌数</font>",
  ["@@chunyu_hp-phase"] = "<font color=\"#AFE1AF\">体力值</font>",
}

local Shizuri = General(extension, "com__shizuri", "com", 4, 4, General.Female)

local melt_downer = fk.CreateTriggerSkill{
  name = "melt_downer",
  anim_type = "control",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    --local victim = player.room:getPlayerById(data.to)
    return target == player and player:hasSkill(self.name) and data.card.type ~= Card.TypeEquip and data.card.sub_type ~= Card.SubtypeDelayedTrick
  end,
  on_cost = function(self, event, target, player, data)
    if player.room:askForSkillInvoke(player, self.name, data, "#melt_downer::"..data.to) then
      self.cost_data = data.to
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local id = EV.askForCardChosen(room, player, room:getPlayerById(self.cost_data), "hes", self.name)
    room:moveCardTo(id, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, "", true, player.id)
    if data.card.color ~= Fk:getCardById(id).color and data.card.type == Fk:getCardById(id).type then
      --table.insertIfNeed(data.nullifiedTargets, self.cost_data)
      EV.nullifiedCard(data, data.card, room:getPlayerById(self.cost_data))
    end
  end,
}

Shizuri:addSkill(melt_downer)

Fk:loadTranslationTable{
  ["com__shizuri"] = "麦野沉利",
  ["designer:com__shizuri"] = "zengyouyu",
  ["melt_downer"] = "原子崩坏",
  [":melt_downer"] = "当你使用基础牌或即时魔法牌指定一个目标后，你可弃置其一张牌；然后若其以此法被弃置的牌与你使用的此牌颜色不同且类别相同，则你使用的此牌对其无效。",
  ["#melt_downer"] = "原子崩坏：你可以弃置%dest的一张牌",
}

local qingji = General(extension, "com__qingji", "com", 3, 3, General.Female)

local ev__yanse = fk.CreateActiveSkill{
  name = "ev__yanse",
  anim_type = "offensive",
  prompt = "#ev__yanse",
  target_num = 1,
  card_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    local target = Fk:currentRoom():getPlayerById(to_select)
    if #U.getMark(Self, "ev__yanse") == 0 then
      return #selected == 0 and not target:isKongcheng() and Self.id ~= to_select
    else
      return #selected == 0 and not target:isKongcheng() and table.contains(U.getMark(Self, "ev__yanse"), to_select)
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local id = EV.askForCardChosen(room, player, target, "h", self.name)
    if id < 0 then return end
    target:showCards({id})
    if Fk:getCardById(id).color == Card.Black then
      room:setPlayerMark(player, "ev__yanse", 0)
      local cards = table.filter(target:getCardIds(Player.Hand), function(id) return Fk:getCardById(id).color == Card.Black end)
      target:showCards(target:getCardIds(Player.Hand))
      room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, nil, true, target.id)
    elseif Fk:getCardById(id).color == Card.Red then
      if room:askForSkillInvoke(target, self.name, data, "#ev__yanse-give::"..player.id) then
        room:moveCardTo(id, Player.Hand, player, fk.ReasonGive, self.name, nil, false, player.id)
        target:drawCards(1, self.name)
        room:setPlayerMark(player, "ev__yanse", target.id)
      end
    end
  end,
}

local yanse_trigger = fk.CreateTriggerSkill{
  name = "#yanse_trigger",
  refresh_events = {fk.Deathed},
  can_refresh = function(self, event, target, player, data)
    return target ~= player and player:hasSkill(self.name) and table.contains(U.getMark(player, "ev__yanse"), target.id)
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "ev__yanse", 0)
  end,
}

local ev__sanmei = fk.CreateTriggerSkill{
  name = "ev__sanmei",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and player.phase == Player.Finish and not player:isKongcheng()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local unshown = table.filter(player:getCardIds(Player.Hand), function(id) return Fk:getCardById(id):getMark("@@shown-inhand") == 0 end)
    if #unshown == 0 then return end
    player:showCards(unshown)
    if table.every(unshown, function(cd) return Fk:getCardById(cd).color == Card.Red end) then
      local targets = {}
      local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
      local end_id = turn_event.id
      U.getEventsByRule(room, GameEvent.MoveCards, 999, function (e)
        for _, move in ipairs(e.data) do
          if move.from ~= nil and move.from ~= player.id and move.toArea == Card.DiscardPile and move.moveReason == fk.ReasonDiscard then
            for _, info in ipairs(move.moveInfo) do
              if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip) and Fk:getCardById(info.cardId).color == Card.Black then
                table.insertIfNeed(targets, move.from)
              end
            end
          end
        end
        return false
      end, end_id)
      local to = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1, "#ev__sanmei-choice", self.name, false)
      if #to > 0 then
        table.insertIfNeed(targets, to[1])
      end
      for _, p in ipairs(targets) do
        room:damage({
          from = player,
          to = room:getPlayerById(p),
          damage = 1,
          damageType = fk.FireDamage,
          skillName = self.name,
        })
      end
    end
  end,
}

ev__yanse:addRelatedSkill(yanse_trigger)
qingji:addSkill(ev__yanse)
qingji:addSkill(ev__sanmei)

Fk:loadTranslationTable{
  ["com__qingji"] = "清姬",
  ["designer:com__qingji"] = "夜之礼赞",
  ["ev__yanse"] = "焰色之吻",
  [":ev__yanse"] = "阶段技（1），你可选择一名其他角色并展示其一张手牌，若此牌为：黑色，你展示其所有手牌，弃置其所有黑色手牌；红色，其可将此牌交给你并摸一张牌，然后你不能以此法选择不为其的角色，直至你以此法展示其黑色牌或其死亡。",
  ["#ev__yanse"] = "焰色之吻：你可选择一名其他角色并展示其一张手牌",
  ["#ev__yanse-give"] = "你可以将此牌交给%dest并摸一张牌",
  ["ev__sanmei"] = "三昧火生",
  [":ev__sanmei"] = "结束阶段，你可展示所有手牌，若均为红色，你选择一名角色及除其之外所有于本回合内因弃置而失去过黑色牌的其他角色，对其各造成1点火焰伤害。",
  ["#ev__sanmei-choice"] = "三昧火生：请选择一名角色",
}

local shangbuhuan = General(extension, "com__shangbuhuan", "com", 4)
local ev__zhuojian = fk.CreateViewAsSkill{
  name = "ev__zhuojian",
  pattern = "slash,jink",
  interaction = function()
    local names = {}
    for _, name in ipairs({"slash","jink"}) do
      local card = Fk:cloneCard(name)
      if (Fk.currentResponsePattern == nil and Self:canUse(card)) or
        (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card)) then
        table.insertIfNeed(names, card.name)
      end
    end
    if #names == 0 then return end
    return UI.ComboBox {choices = names}
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    local room = player.room
    EV.adjustHandCards(room, player, player.hp, self.name)
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and math.abs(player:getHandcardNum() - player.hp) == 1
  end,
  enabled_at_response = function(self, player, response)
    return not response and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and math.abs(player:getHandcardNum() - player.hp) == 1
  end,
}

shangbuhuan:addSkill(ev__zhuojian)

Fk:loadTranslationTable{
  ["com__shangbuhuan"] = "殇不患",
  ["designer:com__shangbuhuan"] = "zengyouyu",
  ["ev__zhuojian"] = "拙剑无式",
  [":ev__zhuojian"] = "回合技，当你需要使用【杀】或【闪】时，若你的体力值与手牌数之差为1，你可将手牌补至或弃置至体力值，视为使用此牌。",
}

local nami = General(extension, "com__nami", "com", 3, 3, General.Female)

local ev__huanchao = fk.CreateTriggerSkill{
  name = "ev__huanchao",
  anim_type = "control",
  events ={fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and 
    (player.phase == Player.Start or (player.phase == Player.Finish and player:getMark("huanchao-turn") > 0))
  end,
  on_cost = function(self, event, target, player, data)
    if player.phase == Player.Start then
      return player.room:askForSkillInvoke(player, self.name)
    elseif player.phase == Player.Finish then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player.phase == Player.Start then
      room:setPlayerMark(player, "huanchao-turn", 1)
    end
    local n = player:getHandcardNum()
    EV.adjustHandCards(room, player:getNextAlive(), n, self.name)
    EV.adjustHandCards(room, player:getLastAlive(), n, self.name)
  end,
}

local ev__zhulang = fk.CreateTriggerSkill{
  name = "ev__zhulang",
  events = {fk.TargetConfirmed},
  anim_type = "drawCards",
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      return player.room:getPlayerById(data.from):getHandcardNum() > player:getHandcardNum()
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}

nami:addSkill(ev__huanchao)
nami:addSkill(ev__zhulang)

Fk:loadTranslationTable{
  ["com__nami"] = "娜美",
  ["designer:com__nami"] = "zengyouyu",
  ["ev__huanchao"] = "唤潮",
  [":ev__huanchao"] = "准备阶段，你可令所有与你相邻的角色将手牌补至或弃置至X张；若如此做，结束阶段，所有与你相邻的角色将手牌补至或弃置至X张（X为你的手牌数）。",
  ["ev__zhulang"] = "逐浪",
  [":ev__zhulang"] = "锁定技，当你成为其他角色使用的牌的目标后，若其手牌数大于你，你摸一张牌。",
}

local chunhu = General(extension, "com__chunhu", "com", 3, 3, General.Female)

local ev__cuihen = fk.CreateTriggerSkill{
  name = "ev__cuihen",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.from
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choices = {"ev__cuihen2"}
    local to = data.from
    if not to:isKongcheng() then table.insert(choices, "ev__cuihen1") end
    local choice = room:askForChoice(to, choices, self.name, "", false, {"ev__cuihen1","ev__cuihen2"})
    if choice == "ev__cuihen2" then
      room:loseHp(to, 1, self.name)
    else
      to:showCards(to:getCardIds(Player.Hand))
      local ids, _ = U.askforChooseCardsAndChoice(player, to:getCardIds(Player.Hand), {"OK"}, self.name, "#ev__cuihen")
      local to_throw = table.filter(to:getCardIds(Player.Hand), function(id) return Fk:getCardById(id).suit ~= Fk:getCardById(ids[1]).suit end)
      if #to_throw > 0 then
        room:moveCardTo(to_throw, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, "", true, to.id)
      end
    end
  end,
}

local ev__chunguang = fk.CreateTriggerSkill{
  name = "ev__chunguang",
  events = {fk.TurnEnd},
  --mute = true,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      local room = player.room
      local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
      if turn_event == nil then return false end
      local uses = {}
      local discards = {}
      local judges = {}
      U.getEventsByRule(room, GameEvent.UseCard, 999, function (e)
        use = e.data[1]
        if use.from == player.id and use.card.id >= 0 then
          table.insertIfNeed(uses, use.card:getSuitString())
          return true
        end
      end, turn_event.id)
      local choices = {}
      U.getEventsByRule(room, GameEvent.MoveCards, 999, function (e)
        for _, move in ipairs(e.data) do
          if move.from == player.id then
            if move.moveReason == fk.ReasonDiscard then
              for _, info in ipairs(move.moveInfo) do
                if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                  table.insertIfNeed(discards, Fk:getCardById(info.cardId):getSuitString())
                end
              end
            end
          end
        end
        return true
      end, turn_event.id)
      U.getEventsByRule(room, GameEvent.Judge, 999, function (e)
        judge = e.data[1]
        if judge.who == player then
          table.insertIfNeed(judges, judge.card:getSuitString())
          return true
        end
      end, turn_event.id)
      local n = 0
      if #uses == 1 then
        n = n + 1
      end
      if #discards == 1 then
        n = n + 1
      end
      if #judges == 1 then
        n = n + 1
      end
      if n > 0 then
        self.cost_data = n
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(self.cost_data, self.name)
  end,
}

chunhu:addSkill(ev__cuihen)
chunhu:addSkill(ev__chunguang)

Fk:loadTranslationTable{
  ["com__chunhu"] = "纯狐",
  ["designer:com__chunhu"] = "小鸟游星羽",
  ["ev__cuihen"] = "粹恨",
  [":ev__cuihen"] = "当你受到伤害后，你可令伤害来源选择一项：1.展示所有手牌并令你选择其中的一张牌，其弃置所有与此牌花色不同的牌；2.失去1点体力。",
  ["ev__cuihen1"] = "展示所有手牌",
  ["ev__cuihen2"] = "失去1点体力",
  ["#ev__cuihen"] = "请选择一张牌，其弃置所有与此牌花色不同的牌",
  ["ev__chunguang"] = "纯光",
  [":ev__chunguang"] = "一名角色的回合结束时，此回合内你的下列牌每有一项花色均相同，你便可摸一张牌：1.判定牌；2.使用过的牌；3.因弃置而失去过的牌。",
}

return extension